package com.itcast.demo.thread_test.service.impl;

import com.itcast.demo.mapper.EmployeeMapper;
import com.itcast.demo.pojo.Employee;
import com.itcast.demo.thread_test.service.AsyncService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CountDownLatch;

@Service
@Slf4j
public class AsyncServiceImpl implements AsyncService {

    @Override
    @Async("asyncServiceExecutor")
    public void executeAsync(List<Employee> employees, EmployeeMapper mapper, CountDownLatch countDownLatch) {

        try {
            log.warn("执行异步任务");
            // 异步线程要做的事情
            mapper.insertAndUpdateLists(employees);
        } catch (Exception e) {
            log.error("异步任务执行失败", e);
        } finally {
            countDownLatch.countDown(); // 很关键，无论上面程序是否异常必须执行countDown，否则await无法释放
        }
    }
}
